from django.shortcuts import render, redirect
from django.views import View
from .models import UserInfo


# Create user views here.

# 用户登录视图类
class LoginView(View):
    def get(self, request):
        # 渲染登录页面
        return render(request, 'user/log-in.html')

    def post(self, request):
        # 从POST请求中获取用户名和密码
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 验证用户名和密码
        try:
            user = UserInfo.objects.get(username=username, password=password)
            # 用户名和密码正确
            # 重定向到首页，并设置cookie
            response = redirect('user:index')
            response.set_cookie('user_name', username)
            response.set_cookie('user_status', '1')
            return response
        except UserInfo.DoesNotExist:
            # 用户名或密码错误
            context = {
                'message': '用户名或密码不正确'
            }
            return render(request, 'user/log-in.html', context=context)


# 用户注册视图类
class RegisterView(View):
    def get(self, request):
        # 渲染注册页面
        return render(request, 'user/register.html')

    def post(self, request):
        # 从POST请求中获取用户名和密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            # 验证用户名是否已存在
            user = UserInfo.objects.get(username=username)
            # 用户名已存在
            context = {
                'message': '用户名已存在'
            }
            return render(request, 'user/register.html', context=context)
        except UserInfo.DoesNotExist:
            # 用户名不存在
            # 创建用户
            user = UserInfo(username=username, password=password)
            user.save()
            # 重定向到登录页面
            return redirect('user:index')


# 用户首页视图函数
def index(request):
    # 获取用户名
    username = request.COOKIES.get('user_name')
    # 渲染首页
    context = {
        'username': username
    }
    return render(request, 'index2.html', context=context)


# 用户退出登录视图函数
def logout(request):
    # 删除cookie
    response = redirect('user:login')
    response.delete_cookie('user_name')
    response.delete_cookie('user_status')
    return response
